package com.xyy.controller;

import com.xyy.common.PageResult;
import com.xyy.common.Result;
import com.xyy.dto.HealthStatisticsDTO;
import com.xyy.entity.Patient;
import com.xyy.service.PatientService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 医生健康数据统计控制器
 */
@Slf4j
@RestController
@RequestMapping("/doctor")
public class DoctorHealthController {

    @Autowired
    private PatientService patientService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取健康数据统计
     */
    @GetMapping("/health-statistics")
    public Result<HealthStatisticsDTO> getHealthStatistics(HttpServletRequest request) {
        try {
            // 从token中获取医生ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long doctorId = jwtUtil.getUserIdFromToken(token);
            if (doctorId == null) {
                return Result.error("无效的token");
            }
            
            // 获取健康数据统计
            HealthStatisticsDTO statistics = patientService.getHealthStatistics();
            
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取健康数据统计失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取患者健康数据列表
     */
    @GetMapping("/patient-health-data")
    public Result<PageResult<Patient>> getPatientHealthData(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            HttpServletRequest request) {
        try {
            // 从token中获取医生ID
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long doctorId = jwtUtil.getUserIdFromToken(token);
            if (doctorId == null) {
                return Result.error("无效的token");
            }
            
            // 获取患者健康数据列表
            PageResult<Patient> result = patientService.getPatientHealthDataPage(current, size, startDate, endDate);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取患者健康数据失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
}
